import 'dart:io';


String jsonPackage = '''
import 'dart:convert' show json;
''';
String extraLine = '''


class EntityFactory<T> {
  static T generateOBJ<T>(jsonRes) {
    T t;
    switch (T.toString()) {
  ''';
String classLine = '''
class EntityFactory<T> {
''';
String endLine = '''
    }
    return t;
  }
}
''';
String classContent = '''
      case '***':
        t = ***.fromJson(jsonRes) as T;
        break;
''';
void main() async {
  var pubSpec = new File('lib/model/entity_factory.dart');
  String filePath = 'lib/model';
  var lines = [];
  if(!pubSpec.existsSync()){
    pubSpec.createSync();
  }
  lines.add(jsonPackage);
  lines.addAll(ergodicForFileName(filePath));
  lines.add(extraLine);

  lines.addAll(ergodicForClassName(filePath).map((s){
    return classContent.replaceAll('***', s);
  }).toList());

  lines.add(endLine);
  pubSpec.writeAsStringSync(lines.join(''));
}

//遍历一个文件夹   获取类名
List<String> ergodicForClassName(String directorPath){
  List<String> classNames = [];
  Directory directory = Directory(directorPath);
  var files = directory.listSync();
  for(var f in files){
    if(f is File){
      print('=================' + f.path);
      if(!f.path.contains('factory.dart')){
        classNames.add(getClassName(f.path));
      }
    }else {
      classNames.addAll(ergodicForClassName(f.path));
    }
  }
  return classNames;
}

//遍历文件名
String prefix = '''
import 'package:flutter_elf/model&&';
''';
List<String> ergodicForFileName (String directorPath){
  List<String> fileNames = [];
  Directory directory = Directory(directorPath);
  var files = directory.listSync();
  for(var f in files){
    if(f is File){
      if(!f.path.contains('factory.dart')){
        String path = f.path.replaceAll('\\', '/');
        fileNames.add(prefix.replaceAll('&&', getFileName(path)));
      }
    }else {
      fileNames.addAll(ergodicForFileName(f.path));
    }
  }
  return fileNames;
}

getFileName(String path){
  return path.substring(path.lastIndexOf("/"));
}


getClassName(String filePath){
  var pubSpec = new File(filePath);
  var lines = pubSpec.readAsLinesSync();
  return lines[2].split(' ')[1];
}


